<!-- 采购单申请 -->
<template>
  <view class="procurementPlan">
    <view class="top mb20">
      <van-cell-group>
        <my-picker
          :form="form"
          name="type_name"
          @click-input="changeFormType"
          :columns="purchaseOrderTypeList"
          value-key="type_name"
          label="采购单类型"
          placeholder="请选择采购单类型"
        ></my-picker>
        <van-field
          @input="changeFormData"
          data-name="purchase_reason"
          :value="form.purchase_reason"
          :norequired="true"
          clearable
          label="采购事由"
          placeholder="请填写采购事由"
        ></van-field>
        <van-field
          @input="changeFormData"
          data-name="back_remarks"
          :value="form.back_remarks"
          clearable
          label="备注"
          placeholder="请填写备注"
        ></van-field>
      </van-cell-group>
    </view>
    <view v-if="form.order_type == '0'">
      <on-setmeal
        @changeFormgoods_info="changeFormgoods_info"
        :list="form.goods_info"
        :order_type="form.order_type"
      ></on-setmeal>
    </view>
    <view class="detail mb20 " v-else>
      <view class="title flexb f26">
        <view> 采购商品明细 </view>
        <view> 已添加{{ form.goods_info.length ? form.goods_info.length : 0 }}件商品 </view>
      </view>
      <view class="list_box">
        <view class="list_item f28 tc mb20" v-for="(item, index) in form.goods_info" :key="index">
          <view class="name flexb">
            <view> 品名:{{ item.goods_name }} </view>
            <view class="details f24" @click="details(item, index)">详情
              <van-icon name="arrow-down" />
            </view>
          </view>
          <view> 供应商：{{ item.supplier_name }} </view>
          <view class="flexb">
            <view v-if="form.order_type != '2'"> 使用类型：{{ item.use_type_name }} </view>
            <view> 数量：{{ item.goods_num }} </view>
          </view>
          <view class="expecte_date flexb"> 期望送货日期：{{ item.expect_time }}</view>
          <view class="del_btn f24">
            <van-button type="default" @click="delProductList(index)">删除</van-button >
          </view>
        </view>
      </view>
    </view>
    <view class="add_btn flexa">
      <van-button plain round color="#62B158" type="danger" @click="onClickShow">+添加商品</van-button>
    </view>
    <view class="btn_box mt100">
      <van-button
        color="#999999"
        type="primary"
        class="primary"
        @click="resetFormData"
        >重置</van-button>
      <!-- <van-button 
        color="#EF9C2B" 
        type="primary" 
        @click="saveToLocal"
        >暂存</van-button> -->
      <van-button
        v-if="form.purchase_sn_detail"
        color="#62B158"
        type="info"
        @click="enitSubmit"
        >修改</van-button>
      <van-button 
        v-else 
        color="#62B158" 
        type="info" 
        @click="submit"
        >提交</van-button>
    </view>

    <!-- 添加商品   @close="show = false" -->
    <my-overlay :show="show" title="添加商品" @close="offShow">
      <!-- 0：套餐 、1：粮油、2：营养餐、 3：自选增量（老师，学生）4：早餐 5：幼儿园 -->
      <view>
        <!-- 套餐 -->
        <view v-if="form.order_type == '0'">
          <van-cell-group>
            <my-picker
              :form="addForm"
              name="menu_name"
              @click-input="changeSetmeal"
              :columns="setmealList"
              value-key="menu_name"
              label="套餐名"
              placeholder="请选择套餐"
            ></my-picker>
            <van-field
              :value="addForm.goods_num"
              name="goods_num"
              data-name="goods_num"
              @input="changeAddFormData"
              required
              clearable
              label="老师数量"
              placeholder="请填写数量"
              input-align="left"
            ></van-field>
            <van-field
              :value="addForm.goods_num_stu"
              name="goods_num_stu"
              data-name="goods_num_stu"
              @input="changeAddFormData"
              required
              clearable
              label="学生数量"
              placeholder="请填写数量"
            ></van-field>
            <van-field
              v-if="form.order_type == '0'"
              :value="addForm.foods_name"
              readonly
              label="包含菜名"
              :maxlength="-1"
              class="baohan"
            >
              <view slot="input" style="height: auto" class="text-goodName"> {{ addForm.foods_name }} </view>
            </van-field>
            <van-field
              :value="addForm.supplier_name"
              name="supplier_name"
              data-name="supplier_name"
              @input="changeAddFormData"
              required
              clearable
              label="供应商名称"
              placeholder="供应商"
            ></van-field>
            <van-field
              :value="addForm.expect_time"
              name="expect_time"
              data-name="expect_time"
              @input="changeAddFormData"
              readonly
              label="期望送货日期"
              placeholder="期望送货日期"
            ></van-field>
            <van-field
              :value="addForm.remark"
              name="remark"
              data-name="remark"
              @input="changeAddFormData"
              clearable
              label="备注"
              placeholder="请填写备注"
            ></van-field>
          </van-cell-group>
        </view>
        <!-- 营养餐 -->
        <view v-if="form.order_type == '2'">
          <van-cell-group>
            <my-picker
              :form="addForm"
              name="cate_name"
              @click-input="changeName"
              :columns="catarrList"
              value-key="cate_name"
              label="分类"
              placeholder="请选择分类"
            ></my-picker>
            <my-picker
              :form="addForm"
              name="goods_name"
              @click-input="changeGoodsList"
              :columns="goods_list"
              value-key="goods_name"
              label="品名"
              placeholder="请选择品名"
            ></my-picker>
            <van-field
              :value="addForm.goods_num"
              name="goods_num"
              data-name="goods_num"
              @input="changeAddFormData"
              @blur="changeNumFormat"
              required
              clearable
              label="数量"
              placeholder="请填写数量"
            ></van-field>
            <van-field
              :value="addForm.unit_name"
              name="unit_name"
              data-name="unit_name"
              @input="changeAddFormData"
              :required="false"
              clearable
              label="单位"
              disabled
            ></van-field>
            <van-field
              :value="addForm.goods_price"
              name="goods_price"
              data-name="goods_price"
              @input="changeAddFormData"
              @blur="changeNumFormat"
              :required="true"
              clearable
              label="单价"
            ></van-field>
            <my-calendar
              :form="addForm"
              name="expect_time"
              @click-input="changeDate"
              label="期望送货日期"
              placeholder="请选择日期"
            ></my-calendar>
            <my-picker
              :form="addForm"
              name="supplier_name"
              @click-input="changeSupplierType"
              :columns="supplierlist"
              value-key="supplier_name"
              label="供应商名称"
              placeholder="请选择供应商"
            ></my-picker>
            <my-calendar
              :form="addForm"
              name="productiontime"
              @click-input="changeDate"
              label="生产日期"
              placeholder="请选择生产日期"
            ></my-calendar>
            <van-field
              v-if="form.order_type == '2'"
              :value="addForm.assurancetime"
              name="assurancetime"
              data-name="assurancetime"
              @input="changeAddFormData"
              required
              clearable
              label="保质期"
              placeholder="请填写保质期"
            ></van-field>
            <van-field
              v-if="form.order_type == '2'"
              :value="addForm.address"
              name="address"
              data-name="address"
              @input="changeAddFormData"
              required
              clearable
              label="产地"
              placeholder="请填写产地"
            ></van-field>
            <view class="upload" v-if="form.order_type == '2'">
              <van-field
                v-if="form.order_type == '2'"
                :value="addForm.filesrc"
                name="filesrc"
                data-name="filesrc"
                required
                clearable
                readonly
                label="检测报告"
                placeholder="请上传检测报告"
              >
                <view slot="input">
                  <van-uploader
                    :deletable="true"
                    @delete="deleteImg"
                    :fileList="fileList"
                    @after-read="afterRead"
                    max-count="1"
                  />
                </view>
              </van-field>
            </view>
            <van-field
              v-if="form.order_type == '2'"
              :disabled="true"
              :value="addForm.nutrition_money | number_format(2)"
              name="nutrition_money"
              data-name="nutrition_money"
              :required="false"
              clearable
              label="小计"
            ></van-field>
            <van-field
              :value="addForm.remark"
              name="remark"
              data-name="remark"
              @input="changeAddFormData"
              clearable
              label="备注"
              placeholder="请填写备注"
            ></van-field>
          </van-cell-group>
        </view>
        <!-- 自选 -->
        <view v-if="form.order_type == '3'">
          <van-cell-group>
            <my-picker
              :form="addForm"
              name="cate_name"
              @click-input="changeName"
              :columns="catarrList"
              value-key="cate_name"
              label="分类"
              placeholder="请选择分类"
            ></my-picker>
            <my-picker
              :form="addForm"
              name="goods_name"
              @click-input="changeGoodsList"
              :columns="goods_list"
              value-key="goods_name"
              label="品名"
              placeholder="请选择品名"
            ></my-picker>
            <van-field
              :value="addForm.unit_name"
              name="unit_name"
              data-name="unit_name"
              @input="changeAddFormData"
              :required="false"
              clearable
              label="单位"
              disabled
            ></van-field>
            <van-field
              :value="addForm.goods_num"
              name="goods_num"
              data-name="goods_num"
              @input="changeAddFormData"
              required
              clearable
              label="数量"
              placeholder="请填写数量"
            ></van-field>
            <my-calendar
              :form="addForm"
              name="expect_time"
              @click-input="changeDate"
              label="期望送货日期"
              placeholder="请选择日期"
            > </my-calendar>
            <my-picker
              :form="addForm"
              name="supplier_name"
              @click-input="changeSupplierType"
              :columns="supplierlist"
              value-key="supplier_name"
              label="供应商名称"
              placeholder="请选择供应商"
            ></my-picker>
            <van-field
              :value="addForm.remark"
              name="remark"
              data-name="remark"
              @input="changeAddFormData"
              clearable
              label="备注"
              placeholder="请填写备注"
            ></van-field>
          </van-cell-group>
        </view>
        <!-- 其他类型的-->
        <view v-if=" form.order_type != '0' && form.order_type != '2' && form.order_type != 3">
          <!-- v-if="form.order_type == '1' || form.order_type == '4' || form.order_type == '5' " 粮油、早餐、幼儿园 (其他类型的) -->
          <van-cell-group>
            <my-picker
              :form="addForm"
              name="cate_name"
              @click-input="changeName"
              :columns="catarrList"
              value-key="cate_name"
              label="分类"
              placeholder="请选择分类"
            ></my-picker>
            <my-picker
              :disabled="!addForm.catarr"
              :form="addForm"
              name="goods_name"
              @click-input="changeGoodsList"
              :columns="goods_list"
              value-key="goods_name"
              label="品名"
              placeholder="请选择品名"
            ></my-picker>
            <van-field
              :value="addForm.use_type_name"
              name="use_type_name"
              data-name="use_type_name"
              @click-input="pickerShow"
              label="使用类型"
              required
              is-link
              readonly
              placeholder="请选择使用类型"
            ></van-field>
            <van-field
              :value="addForm.goods_num"
              name="goods_num"
              data-name="goods_num"
              @input="changeAddFormData"
              required
              clearable
              label="数量"
              placeholder="请填写数量"
            ></van-field>
            <van-field
              :value="addForm.unit_name"
              name="unit_name"
              data-name="unit_name"
              @input="changeAddFormData"
              :required="false"
              clearable
              label="单位"
              disabled
            ></van-field>
            <my-calendar
              :form="addForm"
              name="expect_time"
              @click-input="changeDate"
              label="期望送货日期"
              placeholder="请选择日期"
            ></my-calendar>
            <my-picker
              :form="addForm"
              name="supplier_name"
              @click-input="changeSupplierType"
              :columns="supplierlist"
              value-key="supplier_name"
              label="供应商名称"
              placeholder="请选择供应商"
            ></my-picker>
            <van-field
              :value="addForm.remark"
              name="remark"
              data-name="remark"
              @input="changeAddFormData"
              clearable
              label="备注"
              placeholder="请填写备注"
            ></van-field>
          </van-cell-group>
        </view>
        <view class="btn_style">
          <van-button
            color="#999999"
            type="primary"
            class="primary"
            @click="overlayReset"
            >重置</van-button>
          <van-button
            @click="addToList(false)"
            color="#EF9C2B"
            type="primary"
            v-if="form.order_type != '0'"
            >提交并添加</van-button>
          <van-button 
            @click="addToClose" 
            color="#62B158" 
            type="info"
            >提交并退出</van-button >
        </view>
      </view>
    </my-overlay>

    <!-- 使用类型下拉弹框 -->
    <van-popup :show="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="standingList"
        :value-key="value"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      ></van-picker>
    </van-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isUpdate: false, //true 修改 false提交
      fileList: [],
      dateShow: false,
      addTypeShow: false, //添加类型下拉
      form: {
        goods_info: [],
        purchase_sn_detail: "", //采购单号
        order_type: "",
      },
      show: false, //添加商品
      addForm: {
        goods_price: "", //单价
        remark: "", //备注
        goods_num: null, //数量（学生数量）
        goods_num_stu: null, //老师数量
        unit_name: "", //单位(弹框添加)
        expect_time: "", //期望送货日期
        usetype: "", //使用身份的id
        menu_name: "", //套餐名
        foods_name: "", //包含菜名
        menu_goods_sn: "", //接口获取在传回
        menu_sn: "",
      },
      supplierlist: [], //供应商
      catarrList: [], //分类
      goods_list: [], // 品名
      purchaseOrderTypeList: [], //采购单类型
      showPicker: false, //使用类型下拉
      standingList: ["学生", "老师"],
      setmealList: [], //套餐下拉数据
      menuAdd: true, //开关（套餐追加开关）
    };
  },
  onUnload() {
    uni.removeStorageSync("saveDetail"); // 离开删除 下次进来就没
  },
  onHide() {
    uni.removeStorageSync("saveDetail"); // 离开删除 下次进来就没
  },
  onShow() {
    // 判断是否修改
    if (this.detailData.supplier_name) {
      this.form.goods_info.splice(this.detailData.index, 1, {
        ...this.detailData,
      });
      this.$set(this.form, "goods_info", [...this.form.goods_info]);
      }
  },
  /*监听页面加载，该钩子被调用时*/
  onLoad(options) {
    let pages = getCurrentPages();
    // 判断
    this.form.purchase_sn_detail = options.purchase_sn_detail;
    this.form.order_type = options.order_type;
    this.isUpdate = !!options.purchase_sn_detail;
    if (this.form.purchase_sn_detail || this.form.order_type) {
      uni.setNavigationBarTitle({
        title: "采购单申请(修改)",
      });
      this.getOnEditDetail();
    } else {
      uni.setNavigationBarTitle({
        title: "采购单申请",
      });
    }
  },
  watch: {
    addForm: {
      handler(v) {
        if (v.goods_price && v.goods_num) {
          this.$set( this.addForm, "nutrition_money", v.goods_price * v.goods_num );
        }
      },
      deep: true,
    },
  },
  methods: {    
    /* 获取修改详情数据信息*/
    async getOnEditDetail() {
      let res = await this.$ajax.onEditDetail({
        purchase_sn_detail: this.form.purchase_sn_detail,
      });
      if (res.code == 1) {
        if (res.data.purchaseinfo.order_type == "0") {
          this.form.goods_info = res.data.purchasemenu;
        } else {
          this.form.goods_info = res.data.purchasegoodsinfo;
        }
        this.form.purchase_reason = res.data.purchaseinfo.purchase_reason;
        this.form.back_remarks = res.data.purchaseinfo.back_remarks;
        this.form.order_type = res.data.purchaseinfo.order_type;
        this.form.type_name = res.data.purchaseinfo.type_name;
        var order_type = res.data.purchaseinfo.order_type
        if (order_type) {
          let res = await this.$ajax.onAddbeforedetail({
            order_type:order_type,
          });
          if (res.code ==1) {
            this.catarrList = res.data.catarr; //分类列表
          }
        }

      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });   
      }
    },
    /*修改（按钮-提交）*/
    async enitSubmit() {
      if (this.form.order_type == "0") {
        // 套餐类型的提交
        if (this.form.type_name && this.form.goods_info.length > 0) {
          let res = await this.$ajax.onEditother({
            order_type: this.form.order_type,
            type_name: this.form.type_name,
            purchase_reason: this.form.purchase_reason,
            back_remarks: this.form.back_remarks,
            menu: this.form.goods_info,
            purchase_sn_detail: this.form.purchase_sn_detail,
          });
          if (res.code == 1) {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
            uni.navigateTo({
              url: "../purchaseOrder/purchaseOrder",
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
            uni.navigateTo({
              url: "../purchaseOrder/purchaseOrder",
            });
          }
        }
      } else if (this.form.order_type == "3") {
        // 自选（老师/学生）
        if (this.form.type_name && this.form.goods_info.length > 0) {
          if (this.form.type_name == "添加自选增量(老师)") {
            var typeuse = "1";        
          } else {
            // 添加自选增量(学生)
            var typeuse = "0";
          }
          let res = await this.$ajax.onEditother({
            order_type: this.form.order_type,
            purchase_reason: this.form.purchase_reason,
            back_remarks: this.form.back_remarks,
            usetype: typeuse,
            goods_info: this.form.goods_info,
            purchase_sn_detail: this.form.purchase_sn_detail,
          });
          if (res.code == 1) {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
            uni.navigateTo({
              url: "../purchaseOrder/purchaseOrder",
            });
          }
        } else {
          uni.showToast({
            title: "请先完善数据",
            icon: "none",
          });
        }
      } else {
        if (this.form.type_name && this.form.goods_info.length > 0) {
          // 提交表单
          let res = await this.$ajax.onEditother(this.form);
          if (res.code == 1) {
            uni.showToast({
              title: "提交成功",
              icon: "none",
            });
            setTimeout(() => {
              uni.navigateTo({
                url: "../purchaseOrder/purchaseOrder",
              });
            }, 1000);
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
            setTimeout(() => {
              uni.navigateTo({
                url: "../purchaseOrder/purchaseOrder",
              });
            }, 1000);
          }
        } else {
          uni.showToast({
            title: "请先完善数据",
            icon: "none",
          });
        }
      }
    },

    /*删除（套餐）*/
    changeFormgoods_info(index) {
      var list = Object.assign([], this.form.goods_info);
      list.splice(index, 1);
      this.$set(this.form, "goods_info", [...list]);
      this.$forceUpdate();
    },
    /*小数位*/
    numberToFormat(value, max, min) {
      if (!value) return value;
      max = max || 2;
      min = min || 2;
      value = value + "";
      return parseFloat(value).toLocaleString("en", {
        minimumFractionDigits: max,
        maximumFractionDigits: min,
      });
    },
    changeNumFormat(e) {
      this.$set(this.addForm,  e.target.dataset.name,this.numberToFormat(e.detail.value, 3, 3));
    },
    deleteImg(index) {
      this.fileList.splice(index, 1);
      this.$set(this.addForm, "filesrc", "");
    },
    afterRead(event) {
      const { file } = event.detail;
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      wx.uploadFile({
        url: this.API + "/api/purchasemanage/upload", // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: "file",
        formData: { file: "file" },
        header: {
          token: uni.getStorageSync("token"),
        },
        success: (res) => {
          console.log(JSON.parse(res.data).data);
          console.log(JSON.parse(res.data).data.url,'url111111');
          this.fileList.push({
            ...file,
            url: JSON.parse(res.data).data.fullurl,
            isImage: true,
            // deletable: true
          });
          this.$set(this.addForm, "filesrc", JSON.parse(res.data).data.fullurl); // 上传相对地址或者 绝对地址 ，后期可能需要改
          this.$set(this.addForm, "url", JSON.parse(res.data).data.url); // 上传相对地址或者 绝对地址 ，后期可能需要改
        },
      });
    },
    startUploadFile() {
      wx.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths[0];
          wx.uploadFile({
            url: this.API + "/api/purchasemanage/upload", //仅为示例，非真实的接口地址
            filePath: tempFilePaths,
            name: "file",
            formData: {
              user: "test",
            },
            success: (res) => {
              //do something
            },
          });
        },
      });
    },

    /*获取相关套餐信息*/
    async getCreatemenu(setmeal_sn) {
      let res = await this.$ajax.onCreatemenu({
        setmeal_sn: setmeal_sn,
      });
      if (res.code == 1) {
        this.addForm.foods_name = res.data.menulistnew.foods_name;
        this.addForm.supplier_name = res.data.menulistnew.supplier_name;
        this.addForm.expect_time = res.data.menulistnew.expect_time;
        this.addForm.supplier = res.data.menulistnew.supplier; //供应商id
        this.addForm.menu_goods_sn = res.data.menulistnew.menu_goods_sn;
        this.addForm.goods_name = res.data.menulistnew.goods_name;
        this.addForm.menu_sn = res.data.menulistnew.menu_sn;
        // // 选择完套餐信息后，学生数量老师数量定义默认值
        // this.addForm.goods_num = null; //学生数量
        // this.addForm.goods_num_stu = 0 ; //老师数量
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    },
    /*套餐名*/
    changeSetmeal(key, value) {
      this.$set(this.addForm, "setmeal_sn", value["setmeal_sn"]); //id
      this.$set(this.addForm, key, value["menu_name"]);
      console.log(this.addForm.setmeal_sn);
      if (this.addForm.setmeal_sn) {
        this.getCreatemenu(this.addForm.setmeal_sn);
      }
    },

    /*使用身份*/
    onConfirm(event) {
      const { picker, value, index } = event.detail;
      this.addForm.use_type_name = value;
      this.addForm.usetype = index;
      this.showPicker = false;
    },
    pickerShow() {
      this.showPicker = true;
    },

    /* 单位(添加商品)*/
    async getUnit(goods_sn) {
      let res = await this.$ajax.getUnit({
        goods_sn:goods_sn
      });
      if (res.code == 1) {
        this.addForm.unit_name = res.data;
      }
    },
    /* 获取品名列表(添加商品)*/
    async getGood(cat_id,order_type) {
      let res = await this.$ajax.getGoods({
        cat_id:cat_id,
        order_type:order_type,
      });
      if (res.code == 1) {
        this.goods_list = res.data;
      }
    },

    /*获取采购单类型*/
    async getOrdertype() {
      let res = await this.$ajax.getOrdertype();
      if (res.code == 1) {
        this.purchaseOrderTypeList = res.data;
      }
    },

    /*获取供应商列表*/
    async getSupplierlist() {
      let res = await this.$ajax.getSupplierlist();
      if (res.code == 1) {
        this.supplierlist = res.data;
        this.getSupplierList(res.data); // 供应商列表（vuex）
      }
    },
    /*采购单类型*/
    async changeFormType(key, value) {
      this.$set(this.form, "order_type", value["order_type"]); // 提交给后台的采购单类型ID
      this.$set(this.form, [key], value["type_name"]);

      console.log(this.form.order_type,'类型');
  
      // 每次点击时清空对应的数据
      this.$set(this.form, "purchase_reason", ""); //采购事由
      this.$set(this.form, "back_remarks", "");
      this.$set(this.form, "goods_info", []); 
      // 根据类型判断暂存数据，以及相关下拉数据列信息
      if (this.form.order_type == "3") {
        // 自选（老师、学生）
        if (this.form.type_name == "添加自选增量(老师)") {
          var typeuse = "1";
        } else {
          var typeuse = "0";
        }
        let res = await this.$ajax.onAddbeforedetail({
          order_type: this.form.order_type,
          usetype: typeuse,
        });
        if (res.code == 1) {
          this.catarrList = res.data.catarr; //分类列表（添加商品）
          if (res.data.temp_save.length > 0) {
            this.form.purchase_reason = res.data.temp_save.purchase_reason; //采购事由
            this.form.back_remarks = res.data.temp_save.back_remarks; //备注
            this.form.goods_info = res.data.temp_save.remarks; //暂存数据列信息
          } else {
            this.form.goods_info = []; //清空数据
          }
        }
      }  else if (this.form.order_type == "0") {
        // 套餐类型
        let res = await this.$ajax.onAddbeforedetail({
          order_type: this.form.order_type,
        });
        if (res.code == 1) {
          // 套餐类型的套餐名下拉数据
          if (res.data.all_menus.length >0 ) {
            this.setmealList = res.data.all_menus;
          }else{
            uni.showToast({
              title: "暂无套餐，请联系管理员",
              icon: "none",
            });
          }
          // 判断是否有暂存
          if (res.data) {
            this.form.purchase_reason = res.data.purchase_reason; //采购事由
            this.form.back_remarks = res.data.back_remarks; //备注
            this.form.goods_info = res.data.remarks; //暂存数据列信息
          } else {
            this.form.goods_info = []; //清空数据
          }
        }
      }else if (this.form.order_type) {
        // 判断暂存数据
        let res = await this.$ajax.onAddbeforedetail({
          order_type: this.form.order_type,
        });
        if (res.code == 1) {
          this.catarrList = res.data.catarr; //分类列表（添加商品）
          if (res.data.temp_save.length > 0) {
            this.form.purchase_reason = res.data.temp_save.purchase_reason; //采购事由
            this.form.back_remarks = res.data.temp_save.back_remarks; //备注
            this.form.goods_info = res.data.temp_save.remarks; //暂存数据列信息
          } 
          // else {
          //   this.form.goods_info = []; //清空数据
          // }
        }
      }
    },
    /*品名*/
    changeGoodsList(key, value) {
      this.$set(this.addForm, "goods_sn", value["goods_sn"]); // 对应的品名id 提交给后台的
      this.$set(this.addForm, [key], value["goods_name"]);
      this.getUnit(this.addForm.goods_sn); //单位
    },
    /*添加弹框（分类）*/
    changeName(key, value) {
      this.$set(this.addForm, "catarr", value["catarr"]); // 分类选择的对应id 提交给后台的,
      this.$set(this.addForm, [key], value["cate_name"]);
      // 每次修改分类 要清空产品 + 单位
      this.$set(this.addForm, "goods_name", "");
      this.$set(this.addForm, "goods_sn", "");
      this.$set(this.addForm, "unit_name", "");
      this.getGood(this.addForm.catarr,this.form.order_type); //调品名数据


    },
    /*供应商*/
    changeSupplierType(key, value) {
      this.$set(this.addForm, "supplier", value["supplier"]); // 提交给后台的
      this.$set(this.addForm, [key], value["supplier_name"]);
    },
    changeFormPicker(key, value) {
      this.$set(this.form, [key], value); // 深拷贝
    },
    /*列表重置*/
    resetFormData() {
      this.form.goods_info = [];
      wx.removeStorageSync("form_data");
    },

    /*暂存*/
    // async saveToLocal() {
    //   if (this.form.order_type == "0") {
    //     // 套餐类型的暂存
    //     if (this.form.type_name) {
    //       // 提交套餐暂存数据
    //       let res = await this.$ajax.onTempsave({
    //         order_type: this.form.order_type,
    //         type_name: this.form.type_name,
    //         menu: this.form.goods_info,
    //       });
    //       if (res.code == 1) {
    //         uni.showToast({
    //           title: res.msg,
    //           icon: "none",
    //         });
    //       } else {
    //         uni.showToast({
    //           title: res.msg,
    //           icon: "none",
    //         });
    //       }
    //     }
    //   } else if (this.form.order_type == "3") {
    //     // 自选类型
    //     if ( this.form.order_type &&  this.form.goods_info.length > 0
    //     ) {
    //       if (this.form.type_name == "添加自选增量(老师)") {
    //         var typeuse = "1";
    //       } else {
    //         // 添加自选增量(学生)
    //         var typeuse = "0";
    //       }
    //       let res = await this.$ajax.onTempsave({
    //         order_type: this.form.order_type,
    //         usetype: typeuse,
    //         goods_info: this.form.goods_info,
    //       });
    //       if (res.code == 1) {
    //         uni.showToast({
    //           title: res.msg,
    //           icon: "none",
    //         });
    //       } else {
    //         uni.showToast({
    //           title: res.msg,
    //           icon: "none",
    //         });
    //       }
    //     }
    //   } else {
    //     //其他类型的暂存
    //     if ( this.form.order_type &&  this.form.goods_info.length > 0 ) {
    //       // 提交暂存数据
    //       let res = await this.$ajax.onTempsave(this.form);
    //       if (res.code == 1) {
    //         uni.showToast({
    //           title: res.msg,
    //           icon: "none",
    //         });
    //       } else {
    //         uni.showToast({
    //           title: res.msg,
    //           icon: "none",
    //         });
    //       }
    //     } else {
    //       wx.showToast({
    //         title: "请先完善数据",
    //         icon: "none",
    //       });
    //     }
    //   }
    // },
    formatDate(date) {
      date = new Date(date);
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    },
    /* 日历组件（事件）*/
    changeDate(key, value) {
      this.$set(this.addForm, [key], value);
      this.dateShow = true;
    },
    onDateConfirm(date) {
      this.addForm.expected_date = this.formatDate(date.detail);
      this.dateShow = false;
    },
    onDateClose() {
      this.dateShow = false;
    },
    changeFormData(event) {
      const key = event.target.dataset.name;
      this.form[key] = event.detail;
    },
    changeAddFormData(event) {
      const key = event.target.dataset.name;
      this.addForm[key] = event.detail;
    },
    /*添加*/
    addOnConfirm(e) {
      const { picker, value, index } = e.detail;
      this.addForm.sort = value;
      this.addTypeShow = false;
    },
    /*详情*/
    details(item, index) {
      this.setDetailData({
        ...item,
        index, //下标
      });
      uni.setStorageSync("order_type", this.form.order_type);
      uni.navigateTo({
        url: "../procurementPlan/purchaseDetails?index=" + index + "&order_type=" + this.form.order_type,
      });
    },
    /*删除*/
    delProductList(index) {
      this.form.goods_info.splice(index, 1);
    },
    /*弹框重置*/
    overlayReset() {
      this.addForm = {
        remark: "", //备注
        goods_num: "", //数量
        unit_name: "", //单位(弹框添加)
        expect_time: "", //期望送货日期
        usetype: "", //使用身份的id
        menu_name: "", //套餐名
        foods_name: "", //包含菜名
        menu_goods_sn: "", //接口获取在传回
      };

      if (this.form.order_type == 2) {
        this.deleteImg(0);
      }
    },

    /*提交并添加（弹框）*/
    addToList(flag) {
      // 套餐类型
      if (this.form.order_type == "0") {
        if ( this.addForm.menu_name && this.addForm.supplier_name && this.addForm.expect_time) {
          if (isNaN(this.addForm.goods_num) || isNaN(this.addForm.goods_num_stu) ) {
            wx.showToast({
              title: "请输入数字",
              icon: "none",
            });
          } else {
            if (this.addForm.goods_num > 0 || this.addForm.goods_num_stu > 0) {
              if (this.addForm.goods_num == null) {
                this.addForm.goods_num = 0;
              } else if (this.addForm.goods_num_stu == null) {
                this.addForm.goods_num_stu = 0;
              }
              console.log( this.form.goods_info,this.addForm,' this.form.goods_info');

              this.form.goods_info.push(this.addForm);
              console.log( this.form.goods_info,this.addForm,' this.form.goods_info');
              this.overlayReset();
              wx.showToast({
                title: "添加成功",
                icon: "none",
                duration: 1000,
              });
              if (flag) {
                this.show = false;
              }
            } else {
              wx.showToast({
                title: "至少输入一个数量",
                icon: "none",
              });
            }
          }
        } else {
          wx.showToast({
            title: "请先填写必填数据",
            icon: "none",
            duration: 1000,
          });
        }
      } else if ( this.form.order_type == 1 ||this.form.order_type == 4 ||this.form.order_type == 5) {
        if (
          this.addForm.catarr &&
          this.addForm.goods_sn &&
          this.addForm.goods_num &&
          this.addForm.unit_name &&
          this.addForm.supplier &&
          this.addForm.expect_time &&
          this.addForm.use_type_name
        ) {
          if (isNaN(this.addForm.goods_num)) {
            wx.showToast({
              title: "请输入合法数字",
              icon: "none",
            });
          } else {
            if (this.addForm.goods_num > 0) {
              this.form.goods_info.push(this.addForm);
              this.overlayReset();
              wx.showToast({
                title: "添加成功",
                icon: "none",
                duration: 1000,
              });
              if (flag) {
                this.show = false;
              }
            } else {
              wx.showToast({
                title: "请输入数量",
                icon: "none",
              });
            }
          }
        } else {
          wx.showToast({
            title: "请先填写必填数据",
            icon: "none",
            duration: 1000,
          });
        }
      }else if(  this.form.order_type == 2){
        // 营养餐
        if (
        this.addForm.cate_name &&
        this.addForm.goods_name &&
        this.addForm.goods_num &&
        this.addForm.goods_price &&
        this.addForm.expect_time &&
        this.addForm.supplier &&
        this.addForm.productiontime &&
        this.addForm.assurancetime &&
        this.addForm.address &&
        this.addForm.filesrc
        ) {
          if (this.addForm.goods_num > 0) {
              this.form.goods_info.push(this.addForm);
              this.overlayReset();
              wx.showToast({
                title: "添加成功",
                icon: "none",
                duration: 1000,
              });
              if (flag) {
                this.show = false;
              }
            }else{
              wx.showToast({
                title:"请输入数量",
                icon:"none"
              })
            }
        }else{
          wx.showToast({
            title: "请先填写必填数据",
            icon: "none",
            duration: 1000,
          });
          console.log(this.addForm,'添加数据');
        }

      } else {
        // 判断条件要加
        if ( this.addForm.catarr &&this.addForm.goods_sn &&this.addForm.goods_num &&this.addForm.unit_name &&this.addForm.supplier &&this.addForm.expect_time) {
          if (isNaN(this.addForm.goods_num)) {
            wx.showToast({
              title:"请输入合法数字",
              icon:"none"
            })
          }else{
            if (this.addForm.goods_num > 0) {
              this.form.goods_info.push(this.addForm);
              this.overlayReset();
              wx.showToast({
                title: "添加成功",
                icon: "none",
                duration: 1000,
              });
              if (flag) {
                this.show = false;
              }
            }else{
              wx.showToast({
                title:"请输入数量",
                icon:"none"
              })
            }
          }
        } else {
          wx.showToast({
            title: "请先填写必填数据",
            icon: "none",
            duration: 1000,
          });
        }
      }
    },
    addToClose() {
      this.addToList(true);
    },
    // 添加商品弹框
    async onClickShow() {
      // 不为空判断
      if (this.form.type_name) {
        // 套餐类型=0
        if (this.form.order_type == "0") {
          if (this.form.goods_info.length < 1) {
            this.show = true;
          } else {    
            this.show = false;
            wx.showToast({
              title: "套餐只可添加一条，请在原套餐信息中修改！",
              icon: "none",
            });
          }
        } else {
          this.show = true;
        }
        console.log('触发');
    
      } else {
        wx.showToast({
          title: "请先输入对应的的数据",
          icon: "none",
        });
      }
    },
    /*关闭*/
    offShow() {
      this.show = false;
      this.overlayReset();
    },
    /* 提交*/
    async submit() {
      // 这里也需要加判断啊
      if (this.form.order_type == "0") {
        // 套餐类型的提交
        if (this.form.type_name && this.form.goods_info.length > 0) {
          let res = await this.$ajax.addPurchaseadd({
            order_type: this.form.order_type,
            type_name: this.form.type_name,
            purchase_reason: this.form.purchase_reason,
            back_remarks: this.form.back_remarks,
            menu: this.form.goods_info,
          });
          if (res.code == 1) {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
            setTimeout(() => {
              uni.navigateTo({
                url: "../purchaseOrder/purchaseOrder",
              });
            }, 1000);
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        }
      } else if (this.form.order_type == "3") {
        // 自选（老师/学生）
        if (this.form.type_name && this.form.goods_info.length > 0) {
          if (this.form.type_name == "添加自选增量(老师)") {
            var typeuse = "1";
          } else {
            // 添加自选增量(学生)
            var typeuse = "0";
          }
          let res = await this.$ajax.addPurchaseadd({
            order_type: this.form.order_type,
            purchase_reason: this.form.purchase_reason,
            back_remarks: this.form.back_remarks,
            usetype: typeuse,
            goods_info: this.form.goods_info,
          });
          if (res.code == 1) {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: "请先完善数据",
            icon: "none",
          });
        }
      } else {
        if (this.form.type_name && this.form.goods_info.length > 0) {
          // 提交表单
          let res = await this.$ajax.addPurchaseadd(this.form);
          if (res.code == 1) {
            uni.showToast({
              title: "提交成功",
              icon: "none",
            });
            setTimeout(() => {
              uni.navigateTo({
                url: "../purchaseOrder/purchaseOrder",
              });
            }, 1000);
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: "请先完善数据",
            icon: "none",
          });
        }
      }
    },
  },

  mounted() {
    if (wx.getStorageSync("form_data")) {
      this.form = wx.getStorageSync("form_data");
    }
    this.getSupplierlist(); //
    this.getOrdertype(); //采购单类型
  },

  // 监听用户下拉动作，一般用于下拉刷新
  onPullDownRefresh() {},

  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
};
</script>

<style lang="scss">
// 包含
.baohan {
  ::deep.van-field__body {
    flex-wrap: wrap;
    height: 100rpx;
  }
}
.text-goodName {
  color: #2e88ee;
  width: 380rpx;
  height: 48rpx;
  line-height: 24rpx;
  font-size: 24rpx;
  .van-field__control--custom {
    width: 380rpx;
    height: 48rpx;
    line-height: 24rpx;
    font-size: 24rpx;
  }
}
.upload {
  height: 160rpx;
  .van-field__body {
    height: 180rpx;
  }
}
.van-field__control {
  z-index: 1;
}
.procurementPlan {
  width: 100%;
  min-height: 100vh;
  height: 100%;
  background-color: rgba(244, 244, 244, 1);
  padding-bottom: 15rpx;

  .top {
    width: 100%;
    padding: 0 20rpx;
    background-color: #ffffff;
  }

  // 采购商品明细
  .detail {
    width: 100%;

    .title {
      color: rgba(153, 153, 153, 1);
      padding: 10rpx 20rpx;
      font-family: SourceHanSansSC-regular;
    }

    .list_box {
      .list_item {
        width: 100%;
        line-height: 50rpx;
        background-color: rgba(255, 255, 255, 1);
        color: rgba(16, 16, 16, 1);
        font-family: Arial;
        padding: 10rpx 20rpx;
        text-align: left;

        .name {

          .details {
            color: #2e88ee;
            color: rgba(46, 136, 238, 1);
            font-family: SourceHanSansSC-regular;
          }
        }

        .expecte_date {
          border-bottom: 0.5rpx solid #e7e4e4;
        }

        .del_btn {
          margin-bottom: 15rpx;
          margin-top: 15rpx;

          .van-button {
            color: red;
            width: 120rpx;
            height: 60rpx;
            border-radius: 24rpx;
            border: 1rpx solid #a7a7a7;
            font-size: 24rpx;
            font-family: SourceHanSansSC-regular;
          }
        }
      }
    }
  }
  .add_btn {
    align-items: center;
    margin-top: 42rpx;

    .btn_delStyle {
      width: 100rpx;
      height: 50rpx;
      border: 1px solid #a7a7a7 !important;
      color: red;
    }
  }
  .btn_box {
    display: flex;
    justify-content: space-evenly;
    padding-bottom: 100rpx;

    .van-button {
      width: 180rpx;
      height: 72rpx;
      border-radius: 10rpx;
    }
  }
}
.btn_style {
  display: flex;
  justify-content: space-evenly;
  margin-top: 30rpx;

    .van-button {
      border-radius: 10rpx;
    }
}

</style>